package cn.yunhe.controller;

import cn.yunhe.model.User;
import cn.yunhe.view.ExcleExportService;
import cn.yunhe.view.ExcleView;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Controller
public class UserController {

    @RequestMapping("/export")
    public ModelAndView export(){
        ModelAndView mv = new ModelAndView();
        ExcleView ev = new ExcleView(exportService());
        //文件名
        ev.setFileName("所有角色.xls");
        //设置sql后台参数
//        RoleParams roleParams = new RoleParams();
        //限制1万条
/*        PageParams page = new PageParams();
        page.setStart(0);
        page.setLimit(10000);
        roleParams.setPageParams(page);*/
        //数据，构建对象，省略数据库步骤
        User user1 = new User();
        user1.setUsername("林丹");
        user1.setPassword("000");
        user1.setUserid(1);

        User user2 = new User();
        user2.setUsername("刘翔");
        user2.setPassword("666");
        user2.setUserid(2);

        User user3 = new User();
        user3.setUsername("福娃");
        user3.setPassword("123");
        user3.setUserid(3);

        List<User> list = new ArrayList<User>();
        list.add(user1);
        list.add(user2);
        list.add(user3);

        mv.addObject("userList",list);
        mv.setView(ev);
        return mv;
    }

    @SuppressWarnings({"unchecked"})
    private ExcleExportService exportService(){
        //使用Lambda表达式自定义导出excel规则
        return (Map<String,Object> model, Workbook workbook) -> {
            List<User> userList =(List<User>)model.get("userList");
            Sheet sheet = workbook.createSheet("所有角色");
            Row title = sheet.createRow(0);
            title.createCell(0).setCellValue("编号");
            title.createCell(1).setCellValue("姓名");
            title.createCell(2).setCellValue("密码");

            //遍历列表，生成数据
            for (int i = 0; i < userList.size(); i++) {
                User user = userList.get(i);
                System.out.println(user.getUserid()+"---"+user.getUsername()+"---"+user.getPassword());
                int rowIndex = i+1;
                Row row = sheet.createRow(rowIndex);
                row.createCell(0).setCellValue(user.getUserid());
                row.createCell(1).setCellValue(user.getUsername());
                row.createCell(2).setCellValue(user.getPassword());
            }

        };
    }
}
